import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/Const/IFinal.dart';
import 'package:flutter_app/Main/Deferred.dart' deferred as _Deferred;
import 'package:flutter_app/Main/Localizations.dart';
import 'package:flutter_app/Model/UserModel.dart';
import 'package:flutter_app/Page/Main/Splash/main.dart' deferred as _FirstPage;
import 'package:flutter_app/Util/App/AppUtils.dart';
import 'package:flutter_app/Util/YOSS/YOSS.dart' deferred as _YOSS;
import 'package:flutter_yfree/YFree.dart';
import 'package:flutter_yim/YIM.dart' deferred as _YIM;
import 'package:mobcommonlib/mobcommonlib.dart' deferred as _Mob;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';

Locale? appLocale;

void runApp() {
  yRunApp(
    onLaunchPage: () => _FirstPage.loadLibrary().then((_) => _FirstPage.SplashPage()),
    primarySwatch: Colors.deepOrange,
    onYConfig: () {
      YConfig.appName = "YShop";
      YConfig.themeColor = Color.fromARGB(255, 255, 87, 34);
      YConfig.imagePlaceHolder = "images/loading.png";
      YConfig.navBar = "images/main/statubar.png";
      YConfig.navBarTitleColor = Colors.black;
      YConfig.statubar = "images/main/statubar.png";
      YConfig.statubarTextTheme = SystemUiOverlayStyle.dark;
      YConfig.localizations = localizations;
      YConfig.onLocaleLoad = (locale) async => appLocale = locale;
      YConfig.onHttpHeader = () async {
        return {
          "app-platform-isweb": yIsWeb ? "1" : "0",
          "app-platform-system": yIsWeb ? defaultTargetPlatform.name : Platform.operatingSystem,
          "app-platform-version": yIsWeb ? null : Platform.operatingSystemVersion,
          "app-locale": appLocale!.languageCode,
          "app-version": (await PackageInfo.fromPlatform()).buildNumber,
          "app-sign": globalUserModel?.sign ?? "",
        };
      };
      YConfig.onYPostCommonError = (page, code, message, jkid, kv, callback, onModel, showProgress, showErrorToast, cacheEnable) async {
        if (!(await AppUtils.checkIsLogon(page, goLogin: true))) {
          callback.call(false, null, code!, message!);
          return;
        }
        page.yPost<UserModel>(IFinal.Jkids.refresh_sign, null, (isSuccess, results, code, message) {
          if (isSuccess) {
            AppUtils.saveUserModel(results!.first);
            page.yPost(jkid, kv, callback, onModel: onModel, showProgress: showProgress, showErrorToast: showErrorToast, cacheEnable: cacheEnable);
          } else {
            AppUtils.deleteUserModel();
            yShowBuilder("登录失效，请重新登录\n$message", () => AppUtils.reLaunchApp(goLogin: true), null, false, posTitle: "重新登录");
          }
        }, onModel: (map) => UserModel.fromJson(map), showProgress: true, showErrorToast: false, cacheEnable: false);
      };
    },
    builder: (context, child) => YDeferredBuilder(
      onLoad: () => _Deferred.loadLibrary(),
      onChild: () => _Deferred.Child(child: child!),
    ),
    onYRan: () {
      AppUtils.initUserModel();
      initYIM();
      initShareSDK();
      initYOSS();
    },
  );
}

void initYIM() {
  _YIM.loadLibrary().then((value) {
    _YIM.YIM.init(
      _YIM.YIMOption(
        appKey: IFinal.Configs_Local.third_sdk.yim.appKey,
        debug: false,
      ),
    );
  });
}

void initShareSDK() {
  if (yIsWeb) return;
  SharesdkPlugin.regist(
    ShareSDKRegister()
      ..setupWechat(IFinal.Configs_Local.third_sdk.shareSDK.WeChat_Key, IFinal.Configs_Local.third_sdk.shareSDK.WeChat_Secret, "")
      ..setupQQ(IFinal.Configs_Local.third_sdk.shareSDK.QQ_Key, IFinal.Configs_Local.third_sdk.shareSDK.QQ_Key),
  );
  SharesdkPlugin.uploadPrivacyPermissionStatus(1, (isSuccess) {});
  _Mob.loadLibrary().then((value) {
    _Mob.Mobcommonlib.submitPolicyGrantResult(true, (result, err) {});
  });
}

void initYOSS() {
  _YOSS.loadLibrary().then((value) {
    _YOSS.YOSS.init(
      _YOSS.YOSSOption(
        ossEndpoint: IFinal.Configs_Local.third_sdk.oss.ossEndpoint,
        bucketName: IFinal.Configs_Local.third_sdk.oss.bucketName,
        accessKey: IFinal.Configs_Local.third_sdk.oss.accessKey,
        accessSecret: IFinal.Configs_Local.third_sdk.oss.accessSecret,
        expire: IFinal.Configs_Local.third_sdk.oss.expire,
      ),
    );
  });
}
